package top.jojoace.JPA.util;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;

import javax.persistence.AttributeConverter;
import java.util.HashMap;
import java.util.Map;

/**
 * <h1>实现 数据库类型 与 对象类型 转换</h1>
 *
 *
 *
 */
public class MapAndJson implements AttributeConverter<Map<String,Object >,String> {

    /**
     * 实现JSON转换
     */
    @Autowired
    private ObjectMapper mapper;


    @Override
    public String convertToDatabaseColumn(Map<String,Object> attribute) {
        try {
            return this.mapper.writeValueAsString(attribute);
        }catch (JsonProcessingException e){
            e.printStackTrace();
            throw new RuntimeException("...");
        }
    }

    @Override
    public Map<String, Object> convertToEntityAttribute(String dbData) {
        try {
            return this.mapper.readValue(dbData, HashMap.class);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
            throw new RuntimeException("...");
        }
    }
}
